﻿using System;
using System.Web;

namespace Yyyg.WebUI
{
    public static class HttpContextExt
    {
        /// <summary>
        /// 根据状态码将页面重定向到指定错误页面
        /// </summary>
        /// <param name="p"></param>
        /// <param name="code">状态码</param>
        public static void RedirectToError(this HttpResponseBase p, int code)
        {
            p.Redirect("/Error/Error?code=" + code);
        }

        /// <summary>
        /// 在客户端和session设置一个GuidToken
        /// </summary>
        /// <param name="name">token名称</param>
        /// <param name="path">路径范围</param>
        /// <returns></returns>
        public static void SetTokenByGuid(this HttpContextBase ctx, string name, string path = "/")
        {
            name = "GTK_" + name;
            string value = Guid.NewGuid().ToString("B");
            ctx.Session[name] = value;
            HttpCookie cookie = new HttpCookie(name);
            cookie.Value = value;
            cookie.Path = path;
            ctx.Response.Cookies.Set(cookie);
        }

        /// <summary>
        /// 删除对应Session和Cookie
        /// </summary>
        /// <param name="name">名称</param>
        public static void DelGuidToken(this HttpContextBase ctx, string name)
        {
            name = "GTK_" + name;
            ctx.Session[name] = null;
            ctx.Response.Cookies.Remove(name);
        }

        /// <summary>
        /// 检测客户端GuidToken是否与服务端匹配
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="name">token名称</param>
        /// <returns></returns>
        public static bool CheckGuidToken(this HttpContextBase ctx, string name)
        {
            name = "GTK_" + name;
            string ses = ctx.Session[name]?.ToString();
            string cli = ctx.Request.Cookies[name]?.Value;
            if (ses == null || cli == null) return false;
            return ses.Equals(cli);
        }

        /// <summary>
        /// 获取用户头像相对地址
        /// </summary>
        /// <param name="server"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public static string MapUserHead(this HttpServerUtilityBase server, int uid)
        {
            string hp = "/Content/Images/headimg/head_" + uid + ".jpg";
            if (System.IO.File.Exists(server.MapPath(hp))) return hp + "?r=" + Tools.GetRandMax();
            else return "/Content/Images/headimg/defhead.jpg";
        }

        /// <summary>
        /// 根据请求上下文中的验证信息获取用户ID
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public static int GetUserID(this HttpContextBase ctx)
        {
            if (!ctx.Request.IsAuthenticated) return -1;
            return int.Parse(ctx.User.Identity.Name);
        }
    }
}